//
//  CLLocationExtension.swift
//  WineComing
//
//  Created by xiaozhi on 15/8/5.
//  Copyright (c) 2015年 xiaozhi. All rights reserved.
//

import UIKit
import CoreLocation
let a:Double = 6378245.0;
let ee:Double = 0.00669342162296594323;
extension CLLocation{

    
    func transformToMars()->CLLocation {
    //是否在中国大陆之外
        if self.outOfChina(){
            return self
    }
        var dLat = self.transformLatWithX(self.coordinate.longitude - 105.0,y:self.coordinate.latitude - 35.0)
        var dLon = self.transformLonWithX(self.coordinate.longitude - 105.0,y:self.coordinate.latitude - 35.0)
        let radLat = self.coordinate.latitude / 180.0 * M_PI
        var magic = sin(radLat)
        magic = 1 - ee * magic * magic;
        let sqrtMagic = sqrt(magic);
        dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * M_PI);
        dLon = (dLon * 180.0) / (a / sqrtMagic * cos(radLat) * M_PI);
        return CLLocation(latitude: self.coordinate.latitude + dLat, longitude: self.coordinate.longitude + dLon)
    }
    
    func  outOfChina()->Bool{
        if (self.coordinate.longitude < 72.004 || self.coordinate.longitude > 137.8347) {
            return true
        }
        if (self.coordinate.latitude < 0.8293 || self.coordinate.latitude > 55.8271) {
            return true
        }
            return false
    }
    
    func transformLatWithX(x:Double,y:Double)->Double {
        let c = 0.2*(sqrt(abs(x)))
        var ret:Double = (-100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + c)
        ret += (20.0 * sin(6.0 * x * M_PI) + 20.0 * sin(2.0 * x * M_PI)) * 2.0 / 3.0;
        ret += (20.0 * sin(y * M_PI) + 40.0 * sin(y / 3.0 * M_PI)) * 2.0 / 3.0;
        ret += (160.0 * sin(y / 12.0 * M_PI) + 320 * sin(y * M_PI / 30.0)) * 2.0 / 3.0;
        return ret;
    }
    
   func transformLonWithX(x:Double,y:Double)->Double{
        let c = 0.1 * (sqrt(abs(x)))
        var ret:Double = (300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + c);
        ret += (20.0 * sin(6.0 * x * M_PI) + 20.0 * sin(2.0 * x * M_PI)) * 2.0 / 3.0;
        ret += (20.0 * sin(x * M_PI) + 40.0 * sin(x / 3.0 * M_PI)) * 2.0 / 3.0;
        ret += (150.0 * sin(x / 12.0 * M_PI) + 300.0 * sin(x / 30.0 * M_PI)) * 2.0 / 3.0;
        return ret;
    }
}